package com.aerozhonghuan.archive.service.impl;

import com.aerozhonghuan.archive.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MailServiceImpl implements MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    // 从配置文件中取发件人和收件人地址
    @Value("${spring.mail.from}")
    private String mailFrom;

    @Value("${spring.mail.to}")
    private String mailTo;

    @Value("${spring.mail.cc}")
    private String mailCc;

    @Override
    public void sendEmail(String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailFrom);
        // 将邮件收件人地址拆分为数组（多个地址以逗号分隔）
        if (mailTo != null && !mailTo.trim().isEmpty()) {
            String[] toArray = mailTo.split("\\s*,\\s*");
            message.setTo(toArray);
        }
        if (mailCc != null && !mailCc.trim().isEmpty()) {
            // 去除引号（如果有的话）和多余的空格
            String ccProcessed = mailCc.replace("\"", "").trim();
            String[] ccArray = ccProcessed.split("\\s*,\\s*");
            message.setCc(ccArray);
        }
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("邮件发送成功，主题：{}", subject);
        } catch (Exception e) {
            logger.error("邮件发送失败", e);
            throw e;
        }
    }
}
